/*
编写 : Hexh
时间 : 2012-9-12 14:48:01
*/
using System;
using System.ComponentModel;
using System.Web.Mvc;
using FSBS.Core.Entity;
using FSBS.Facade;
using HMIS.FrameWork;
using HMIS.Infrastructure.Core.Authority;
using HMIS.Infrastructure.Facade.Authority;
using HMIS.MVC.CommonSupport;
using HMIS.MVC.ViewModel;
using Iesi.Collections.Generic;

namespace HMIS.MVC.Controllers
{
	/// <summary>
	///	 the mvc class of FsbsQmStrc
	/// </summary>
	public class FsbsQmStrcController : BaseController
	{

		private readonly IFsbsQmStrcFacade FsbsQmStrcFacade;
		private readonly IFsbsQmCrifFacade FsbsQmCarinfoFacade;
		private readonly IHospUserFacade HospUserFacade;
		private readonly CurrentUser CUser = new CurrentUser();

		public FsbsQmStrcController(IFsbsQmStrcFacade FsbsQmStrcFacade, IFsbsQmCrifFacade FsbsQmCarinfoFacade, IHospUserFacade HospUserFacade)
		{
			this.FsbsQmStrcFacade = FsbsQmStrcFacade;
			this.FsbsQmCarinfoFacade = FsbsQmCarinfoFacade;
			this.HospUserFacade = HospUserFacade;
		}

		[ExtResult]
		[Description("添加修改汽贸出入库单信息")]
		public ActionResult SaveOrUpdate()
		{
			FsbsQmStrc entity = FsbsQmStrcFacade.Get(Request["Id"]);
			if (entity == null)
			{
				entity = new FsbsQmStrc
				{
					Id = Request["Id"],
					//QMInout = Request["QMInout"],
					QMInout = "qmio_0",
					QMType = Request["QMType"],
					ProviderId = Request["ProviderId"],
					DepartmentId = CUser.UserInfo.DepartmentId,
					OperuserId = CUser.UserInfo.Id,
					Description = Request["Description"],
					QMState = QMState.Edit
				};
			}
			else
			{
				if (entity.QMState != QMState.Edit)
					throw new ValidationException("该汽贸单状态不可修改.");

				// set new value..
				entity.QMType = Request["QMType"];
				entity.ProviderId = Request["ProviderId"];
				entity.Description = Request["Description"];
			}
			// 保存信息
			FsbsQmStrcFacade.SaveOrUpdate(entity);

			return this.JsonFormat(new ExtResult { success = true, id = entity.Id });
		}

		[ExtResult]
		[Description("汽贸-入库单-添加车辆")]
		public ActionResult SaveOrUpdateCarInfo()
		{
			if (String.IsNullOrEmpty(CUser.UserInfo.DepartmentId))
				throw new ValidationException("当前用户[" + CUser.UserInfo.Name + "]无法录入整车信息。<br>请检查用户是否配置所属展场信息。");

			FsbsQmCrif car_Entity;
			FsbsQmStrc qm_Entity = FsbsQmStrcFacade.GetOrNull(Request["StoreId"]);

			//判断是否可以添加修改信息
			if (qm_Entity != null && qm_Entity.QMState != QMState.Edit)
				throw new ValidationException("该汽贸单状态不可修改.");

			//读取是否已经有车辆信息
			if (String.IsNullOrEmpty(Request["Id"]))
			{
				logger.Info("+++录入新车信息");
				car_Entity = new FsbsQmCrif
				{
					//TODO... ID卡信息
					IccardId = Request["Iccarduid"],
					Iccarduid = Request["Iccarduid"],
					KeyIccardId = Request["KeyIccarduid"],
					KeyIccarduid = Request["KeyIccarduid"],

					DepartmentId = CUser.UserInfo.DepartmentId,
					Brand = Request["Brand"],
					Series = Request["Series"],
					Model = Request["Model"],
					Color = Request["Color"],
					EnginId = Request["EnginId"],
					FrameId = Request["FrameId"],
					ProdDate = DateTime.Parse(Request["ProdDate"]),
					Mileage = Request["Mileage"] == null ? 0 : decimal.Parse(Request["Mileage"]),
					MarketPrice = Request["MarketPrice"] == null ? 0 : decimal.Parse(Request["MarketPrice"]),
					AtmGjb = Request["AtmGjb"] == null ? 0 : int.Parse(Request["AtmGjb"]),
					AtmBt = Request["AtmBt"] == null ? 0 : int.Parse(Request["AtmBt"]),
					AtmSms = Request["AtmSms"] == null ? 0 : int.Parse(Request["AtmSms"]),
					AtmDyq = Request["AtmDyq"] == null ? 0 : int.Parse(Request["AtmDyq"]),
					AtmBxk = Request["AtmBxk"] == null ? 0 : int.Parse(Request["AtmBxk"]),
					AtmKey = Request["AtmKey"] == null ? 0 : int.Parse(Request["AtmKey"]),
					AtmMast = Request["AtmMast"] == null ? 0 : int.Parse(Request["AtmMast"]),
					AtmWiper = Request["AtmWiper"] == null ? 0 : int.Parse(Request["AtmWiper"]),
					AtmCertificate = Request["AtmCertificate"] == null ? 0 : int.Parse(Request["AtmCertificate"]),
					Description = Request["Description"],
					State = CarState.ToStore
				};
			}
			else
			{
				car_Entity = FsbsQmCarinfoFacade.Load(Request["Id"]);
				car_Entity.IccardId = Request["IccardId"];
				car_Entity.Iccarduid = Request["Iccarduid"];
				car_Entity.KeyIccardId = Request["KeyIccardId"];
				car_Entity.KeyIccarduid = Request["KeyIccarduid"];
				car_Entity.Brand = Request["Brand"];
				car_Entity.Series = Request["Series"];
				car_Entity.Model = Request["Model"];
				car_Entity.Color = Request["Color"];
				car_Entity.EnginId = Request["EnginId"];
				car_Entity.FrameId = Request["FrameId"];
				car_Entity.ProdDate = Request["ProdDate"] == null ? DateTime.MinValue : DateTime.Parse(Request["ProdDate"]);
				car_Entity.Mileage = Request["Mileage"] == null ? 0 : decimal.Parse(Request["Mileage"]);
				car_Entity.MarketPrice = Request["MarketPrice"] == null ? 0 : decimal.Parse(Request["MarketPrice"]);
				car_Entity.AtmGjb = Request["AtmGjb"] == null ? 0 : int.Parse(Request["AtmGjb"]);
				car_Entity.AtmBt = Request["AtmBt"] == null ? 0 : int.Parse(Request["AtmBt"]);
				car_Entity.AtmSms = Request["AtmSms"] == null ? 0 : int.Parse(Request["AtmSms"]);
				car_Entity.AtmDyq = Request["AtmDyq"] == null ? 0 : int.Parse(Request["AtmDyq"]);
				car_Entity.AtmBxk = Request["AtmBxk"] == null ? 0 : int.Parse(Request["AtmBxk"]);
				car_Entity.AtmKey = Request["AtmKey"] == null ? 0 : int.Parse(Request["AtmKey"]);
				car_Entity.AtmMast = Request["AtmMast"] == null ? 0 : int.Parse(Request["AtmMast"]);
				car_Entity.AtmWiper = Request["AtmWiper"] == null ? 0 : int.Parse(Request["AtmWiper"]);
				car_Entity.AtmCertificate = Request["AtmCertificate"] == null ? 0 : int.Parse(Request["AtmCertificate"]);
				car_Entity.Description = Request["Description"];
			}
			// 保存信息
			FsbsQmCarinfoFacade.SaveOrUpdate(car_Entity);

			if (String.IsNullOrEmpty(Request["Id"]))
				FsbsQmCarinfoFacade.AddStrlInfo(car_Entity.Id, Request["StoreId"]);

			return this.JsonFormat(new ExtResult { success = true, id = car_Entity.Id });
		}

		[ExtResult]
		[Description("汽贸-出库单-添加车辆")]
		public ActionResult StoreOutAddCars()
		{
			FsbsQmStrc qmEntity = FsbsQmStrcFacade.Get(Request["StoreId"]);
			if (qmEntity.QMState != QMState.Edit)
				throw new ValidationException("该汽贸单状态不可修改.");

			FsbsQmCrif car_Entity;
			string[] Ids = Request["Ids"].Split(',');
			for (int i = 0; i < Ids.Length; i++)
			{
				if (!string.IsNullOrEmpty(Ids[i]))
				{
					// get the entity.
					car_Entity = FsbsQmCarinfoFacade.Get(Ids[i]);
					// set new value..
					if (car_Entity.State != CarState.InStore)
						throw new ValidationException("车辆[" + car_Entity.Id + "]状态不可出库，请检查.");

					if (!qmEntity.Cars.Contains(car_Entity))
						qmEntity.Cars.Add(car_Entity);
				}
			}

			FsbsQmStrcFacade.SaveOrUpdate(qmEntity);
			return this.JsonFormat(new ExtResult { success = true, id = qmEntity.Id });
		}


		[ExtResult]
		[Description("汽贸-入库")]
		public ActionResult StorageIn()
		{
			if (!String.IsNullOrEmpty(Request["Ids"]))
			{
				string[] Ids = Request["Ids"].Split(',');
				for (int i = 0; i < Ids.Length; i++)
				{
					if (!string.IsNullOrEmpty(Ids[i]))
					{
						FsbsQmStrc qmEntity = FsbsQmStrcFacade.Get(Ids[i]);
						if (qmEntity.QMState != QMState.Edit)
							throw new ValidationException("该汽贸单状态不可修改.");
						qmEntity.QMState = QMState.StoreIn;
						qmEntity.CheckuserId = CUser.UserInfo.Id;
						//入库车辆
						foreach (FsbsQmCrif carEntity in qmEntity.Cars)
						{
							carEntity.StoreIndt = System.DateTime.Now;
							carEntity.State = CarState.InStore;
						}
						FsbsQmStrcFacade.SaveOrUpdate(qmEntity);
					}
				}
			}

			return this.JsonFormat(new ExtResult { success = true });
		}

		[ExtResult]
		[Description("汽贸-出库")]
		public ActionResult StorageOut()
		{
			if (!String.IsNullOrEmpty(Request["Ids"]))
			{
				string[] Ids = Request["Ids"].Split(',');
				for (int i = 0; i < Ids.Length; i++)
				{
					if (!string.IsNullOrEmpty(Ids[i]))
					{
						FsbsQmStrc qmEntity = FsbsQmStrcFacade.Get(Ids[i]);
						if (qmEntity.QMState != QMState.Edit)
							throw new ValidationException("商品车出库单[" + qmEntity.Id + "]状态不可修改.");
						qmEntity.QMState = QMState.StoreOut;
						qmEntity.CheckuserId = CUser.UserInfo.Id;
						//入库车辆
						foreach (FsbsQmCrif carEntity in qmEntity.Cars)
						{
							if (carEntity.State != CarState.InStore)
								throw new ValidationException("商品车出库单[" + qmEntity.Id + "],车辆[" + carEntity.Id + "]状态为" + carEntity.State.ToString() + ",不可出库。");
							carEntity.StoreOutdt = System.DateTime.Now;
							carEntity.State = CarState.Selled;
						}
						FsbsQmStrcFacade.SaveOrUpdate(qmEntity);
					}
				}
			}

			return this.JsonFormat(new ExtResult { success = true });
		}

		[ExtResult]
		[Description("删除汽贸-出入库单")]
		public ActionResult Delete()
		{
			FsbsQmStrc qm_Entity = FsbsQmStrcFacade.Load(Request["Id"]);
			if (qm_Entity.QMState != QMState.Edit)
			{
				return this.JsonFormat((new ExtResult { success = false, msg = "不能删除：" + Request["Id"] }));
			}
			FsbsQmStrcFacade.Delete(Request["Id"]);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[ExtResult]
		[Description("汽贸-出入库单-删除车辆")]
		public ActionResult DeleteCar()
		{
			FsbsQmStrc qmEntity = FsbsQmStrcFacade.Get(Request["StoreId"]);
			if (qmEntity.QMState != QMState.Edit)
				throw new ValidationException("该出入库单状态不可修改.");

			FsbsQmCrif car_Entity = FsbsQmCarinfoFacade.Get(Request["Id"]);
			if (qmEntity.QMInout == "qmio_0")
			{
				logger.Debug("删除商品车信息..." + Request["Id"]);
				FsbsQmCarinfoFacade.Delete(Request["Id"]);
			}
			qmEntity.Cars.Remove(car_Entity);
			FsbsQmStrcFacade.SaveOrUpdate(qmEntity);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[ExtResult]
		[Description("物理删除FsbsQmStrc基本资料")]
		public ActionResult PhysicsDelete()
		{
			FsbsQmStrcFacade.PhysicsDelete(Request["Id"]);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[Description("获取FsbsQmStrc清单")]
		public ActionResult GetPlist()
		{
			long total;
			var data = FsbsQmStrcFacade.GetPlist(
				Request["qmInOut"],
				Request["q_query"],
				int.Parse(Request["start"] == null ? "0" : Request["start"]),
				int.Parse(Request["limit"] == null ? "0" : Request["limit"]),
				Request["sort"],
				Request["dir"],
				this.DesDataFilter(Request["filter"]),
				out total);
			//TODO : 修改关联查询返回的类型
			return this.JsonFormat(
				new ExtGirdData<FsbsQmStrc> { total = total, data = data },
				new string[] { "CustomType" });
		}


		[Description("获取汽贸-库存变动-车辆清单")]
		public ActionResult GetCarPlist()
		{
			long total;
			var data = FsbsQmCarinfoFacade.GetPlistByStoreId(
				Request["storeid"],
				Request["q_query"],
				int.Parse(Request["start"] == null ? "0" : Request["start"]),
				int.Parse(Request["limit"] == null ? "0" : Request["limit"]),
				Request["sort"],
				Request["dir"],
				this.DesDataFilter(Request["filter"]),
				out total);
			return this.JsonFormat(
				new ExtGirdData<FsbsQmCrif> { total = total, data = data },
				new string[] { "CustomType" });
		}

		[Description("获取FsbsQmStrc信息")]
		public ActionResult GetById()
		{
			var entity = FsbsQmStrcFacade.Get(Request["Id"]);
			return this.JsonFormat(
			   new ExtFormLoadData<FsbsQmStrc> { data = new FsbsQmStrc[] { entity } }, new string[] { "AuthorizeUsers" }
			   );
		}

		[ExtResult]
		[Description("判断FsbsQmStrc字段是否唯一")]
		public ActionResult IsFieldExist()
		{
			var result = FsbsQmStrcFacade.IsFieldExist(Request["FieldName"], Request[Request["FieldName"]], Request["Id"]);
			return this.JsonFormat(new ExtResult { success = !result, msg = "已存在相同的项!" });
		}

		[Description("返回出入库单状态")]
		public ActionResult GetQmState()
		{
			var result = EnumDescription.ToList<QMState>();
			return this.JsonFormat(result);
		}

		[Description("返回商品车库存状态")]
		public ActionResult GetCarState()
		{
			var result = EnumDescription.ToList<CarState>();
			return this.JsonFormat(result);
		}

	}
}
